import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_form_core/provider/base_request_form_provider.dart';
import 'package:x3_form_core/business_components/base_request_form_container.dart';
import 'package:x3_component_core/components/button_components/base_custom_switch_button.dart';

class BaseRequestFormInputSwitch extends StatefulWidget {

  final BaseHttpRequestModel request;

  final RequestSaveData requestSaveData;

  const BaseRequestFormInputSwitch({Key key, this.request, this.requestSaveData}) : super(key: key);

  @override
  _BaseRequestFormInputSwitchState createState() => _BaseRequestFormInputSwitchState();

}

class _BaseRequestFormInputSwitchState extends State<BaseRequestFormInputSwitch> {

  BaseRequestFormProvider _baseRequestFormProvider;

  bool _value;

  @override
  Widget build(BuildContext context) {
    _baseRequestFormProvider = BaseRequestFormProvider.of(context);
    _value = _baseRequestFormProvider.getDataSource(widget.request) ?? false;
    bool isReadonly = _baseRequestFormProvider.isReadonly(widget.request);
    return BaseRequestFormContainer(
      request: widget.request,
      onPress: isReadonly == false ? () => {_onChange()} : null,
      child: Stack(
        children: [
          Align(
            alignment: Alignment(-1, 0.11),
            child: AbsorbPointer(
              absorbing: true,
              child: BaseCustomSwitchButton(
                value: _value,
                onChanged: (v) {},
              ),
            ),
          )
        ],
      ),
    );
  }

  void _onChange() {
    _value = !_value;
    setState(() {
      _baseRequestFormProvider.setDataSource(widget.request, _value);
      if (widget.requestSaveData != null) widget.requestSaveData(widget.request, _baseRequestFormProvider.getMapDataSource(widget.request));
    });
  }

}
